//
//  ViewController.swift
//  AliBaiChuan
//
//  Created by 郑东喜 on 2017/2/7.
//  Copyright © 2017年 郑东喜. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    
    static let shared = ViewController()
    
    //警告框输入的文字获取
    var tfText : String = ""
    
    //表格
    fileprivate lazy var tableView : UITableView = {
        let tt : UITableView = UITableView.init(frame: self.view.bounds, style: .plain)
        tt.delegate = self
        ///自动拉伸设置
        tt.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        tt.dataSource = self
        return tt
    }()
    
    ///用户信息
    fileprivate lazy var _session : ALBBSDK = {
        let _se : ALBBSDK = ALBBSDK()
        return _se
    }()
    
    //会话session
    fileprivate lazy var _alSession : ALBBSession = {
        let _se : ALBBSession = ALBBSession()
        return _se
    }()
    
    ///数据源
    fileprivate lazy var dataSource : NSMutableArray = {
        let daa : NSMutableArray = ["商品页面","店铺","授权登陆","用户信息","用户退出","我的购物车","我的订单","打开指定url","添加商品到购物车","真实商品详情页地址","登陆状态检查"]
        return daa
    }()
    
    ///loginStatus
    fileprivate var isLogin : String = ""
    

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        setUI()
    }
}

extension ViewController : UITableViewDelegate,UITableViewDataSource {
    func setUI() -> Void {
        view.addSubview(tableView)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
        
        if  cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "cellID")
        }

        cell?.textLabel?.text = self.dataSource[indexPath.row] as? String
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
            
            //商品指定页
        case 0:
            
            self.openGoods()
             break
            
            ///店铺
        case 1:
            self.openShop()
            break
            
            ///打开授权登陆
        case 2:
            
            setLogin()
            break
            
            ///个人信息
        case 3:
            self.navigationController?.pushViewController(UserInfoVC(), animated: true)
            break
            ///退出
        case 4:
            self.logout()
            break
            ///我的购物车
        case 5:
            self.openShooCar()
            
//            self.openItemDetatilMyPage(itemId: "543256891698")
            break
            
        ///我的订单
        case 6:
            self.showSelectIndex()
            
            break
            
        ///打开指定url
        case 7:
            
            self.alertWithInput()
            break
        ///指定商品添加到购物车
        case 8:
            self.addToCart(shopId: "543256891698")
            break
        
        ///真实商品名
        case 9:
//            print("\((#file as NSString).lastPathComponent):(\(#line))",ALiTradeEnv.itemURL(withItemType: 0, itemID: "543256891698") as Any)
            
            self.navigationController?.pushViewController(WebView(), animated: true)
            break
            ///登陆状态
        case 10:
            self.islogin()
        break
            
        default:
            break
        }
    }
}

extension ViewController {
    
    /**
     * 创建我的订单列表页面
     *
     * @param status 所要展示订单的订单状态
     *  0: 为全部订单
     *  1: 为待付款订单
     *  2: 为待发货订单
     *  3: 为待收货订单
     *  4: 为待评价订单
     * @param isAllOrder  是否显示全部订单
     *
     *  YES: 显示全部订单
     *  NO : 显示ISV自己创建的订单
     *
     * @return 我的订单列表页面
     */
    // MARK:- 我的订单
    fileprivate func mydetailOrders(iiitn : Int) -> Void {
        let page = AlibcTradePageFactory.myOrdersPage(iiitn, isAllOrder: true)
        let service = AlibcTradeSDK.sharedInstance().tradeService()
        
        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
        showParams.openType = .H5
        
        
        service?.show(showParams.isNeedPush ? self.navigationController! : self,
                      page: page,
                      showParams:showParams,
                      
                      taoKeParams: nil,
                      trackParam: ["track_key":"track_value"],
                      tradeProcessSuccessCallback: { (result) in
                        print("\((#file as NSString).lastPathComponent):(\(#line))",result as Any)
                        
                    }, tradeProcessFailedCallback: { (error) in
                        
                    })
    }
    
    // MARK:- 打开商品
    fileprivate func openGoods() -> Void {
        let page = AlibcTradePageFactory.itemDetailPage("543256891698")
        let service = AlibcTradeSDK.sharedInstance().tradeService()
        
        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
        showParams.openType = .H5
        
        ///加入词句调用天猫
//        showParams.linkKey = "tmall_scheme"
        service?.show(showParams.isNeedPush ? self.navigationController! : self,
                      page: page,
                      showParams:showParams,
                      
                      taoKeParams: nil,
                      trackParam: ["track_key":"track_value"],
                      tradeProcessSuccessCallback: { (result) in
                        print("\((#file as NSString).lastPathComponent):(\(#line))",result as Any)
                        
                    }, tradeProcessFailedCallback: { (error) in
                        
                    })
    }
    
    // MARK:- 店铺
    fileprivate func openShop() -> Void {
        let page = AlibcTradePageFactory.shopPage("107922698")
        let service = AlibcTradeSDK.sharedInstance().tradeService()
        
        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
        showParams.openType = .auto
        
        service?.show(showParams.isNeedPush ? self.navigationController! : self,
                      page: page,
                      showParams:showParams,
                      taoKeParams: nil,
                      trackParam: ["track_key":"track_value"],
                      tradeProcessSuccessCallback: { (result) in
                        print("\((#file as NSString).lastPathComponent):(\(#line))",result as Any)
                    }, tradeProcessFailedCallback: { (error) in
                        
                    })
    }
    
    // MARK:- 购物车
    func openShooCar() -> Void {
        shoppingCar()
    }

    // MARK:- 用户退出
    fileprivate func logout() -> Void {
        _session.logout()
        
        print("\((#file as NSString).lastPathComponent):(\(#line))",_alSession.isLogin())
        ///1.检查登陆状态
        if _alSession.isLogin() == true {
            showWithAlert(data: "退出成功")
            
            localSave.removeObject(forKey: "loginStatus")
            localSave.synchronize()
        } else {
            showWithAlert(data: "未登陆")
            localSave.removeObject(forKey: "loginStatus")
            localSave.synchronize()
        }
    
    }
    
    // MARK:- 用户登陆
    fileprivate func setLogin() -> Void {
        
        GetUserModel.shared.getUData { (name, oId, SID, headUrl, _) in
            let _data = "用户名: \(name)" + "\n 头像地址：\(headUrl)" + "\n openID : \(oId)" + "\n openSID : \(SID))"
            showWithAlert(data: _data)
        }
    }

    
    
    // MARK:- 打开指定url页面
    fileprivate func openURL(urlStr : String?) -> Void {
        
        if let strVal = urlStr {
            print(strVal)
            let page = AlibcTradePageFactory.page(urlStr!)
            let service = AlibcTradeSDK.sharedInstance().tradeService()
            
            let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
            showParams.openType = .H5
            
            ///加入词句调用天猫
            service?.show(showParams.isNeedPush ? self.navigationController! : self,
                          page: page,
                          showParams:showParams,
                          
                          taoKeParams: nil,
                          trackParam: ["track_key":"track_value"], tradeProcessSuccessCallback: { (result) in
                            print("\((#file as NSString).lastPathComponent):(\(#line))",result?.payResult?.paySuccessOrders as Any)
                            
                            
            }, tradeProcessFailedCallback: { (error) in
                
            })
        }else {
            print("str is nil")
        }

    
    }
    
    // MARK:- 添加商品到购物车
    func addToCart(shopId : String) -> Void {
        let page = AlibcTradePageFactory.addCartPage(shopId)
        let service = AlibcTradeSDK.sharedInstance().tradeService()
        
        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
        showParams.openType = .H5
        
        
        ///加入词句调用天猫
        service?.show(showParams.isNeedPush ? self.navigationController! : self,
                      page: page,
                      showParams:showParams,
                      
                      taoKeParams: nil,
                      trackParam: ["track_key":"track_value"],
                      tradeProcessSuccessCallback: { (result) in
                        print("\((#file as NSString).lastPathComponent):(\(#line))",result as Any)
                        print("\((#file as NSString).lastPathComponent):(\(#line))",result?.result.hashValue as Any)
                        
                        //获取到完成的值（添加到购物车成功或者是支付成功）
                       let resultID = result?.result.hashValue
                        
                        ///加入购物车成功
                        if resultID == 0 {
                        
                            ///延时执行
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: { 
                                self.openShooCar()
                            })
                            
                            
                        ///支付成功
                        } else {
                            ///延时执行
                            
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
                                self.openShooCar()
                            })
                        }
                        
                        
                    }, tradeProcessFailedCallback: { (error) in
                        
                    })
        
    }
    
    // MARK:- 获取登陆状态
    func islogin() -> Void {
        if _alSession.isLogin() == true {
            isLogin = "true"
        } else {
            isLogin = "false"
        }
        
        //提示登陆状态
        showWithAlert(data: isLogin)
    }

}

///nsstring获取
extension ViewController {
    // MARK:- 获取淘宝首页地址
    func getTB() -> String {
        let tbUrl = ALiTradeEnv.taobaoHomeURL()
        print("\((#file as NSString).lastPathComponent):(\(#line))",tbUrl as Any)
        
        return tbUrl!
    }
}


extension ViewController {
    ///提示框
   
    
    ///显示订单类型
    func showSelectIndex()-> Void {
        ///提示框显示结果
        let alertVc = UIAlertController.init(title: "提示", message: "选择订单类型", preferredStyle: .actionSheet)
        
        alertVc.addAction(UIAlertAction.init(title: "全部订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("0")!)
        }))
        
        alertVc.addAction(UIAlertAction.init(title: "待付款订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("1")!)
        }))
        alertVc.addAction(UIAlertAction.init(title: "待发货订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("2")!)
        }))
        alertVc.addAction(UIAlertAction.init(title: "待收货订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("3")!)
        }))
        alertVc.addAction(UIAlertAction.init(title: "待评价订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("4")!)
        }))
        
        alertVc.addAction(UIAlertAction.init(title: "确定", style: .default, handler: nil))
        
        self.present(alertVc, animated: true, completion: nil)
    
    }
    
    // MARK:- 输入URL
    func alertWithInput() -> Void {

        let alertController = UIAlertController(title: "系统登录",
                                                message: "请输入用户名和密码", preferredStyle: .alert)
        alertController.addTextField {
            (textField: UITextField!) -> Void in
            textField.placeholder = "情书URL"
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "好的", style: .default, handler: {
            action in
            //也可以用下标的形式获取textField let login = alertController.textFields![0]
            let login = alertController.textFields!.first!
            
            print("用户名：\(login.text)")
            
            self.openURL(urlStr: login.text)
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

extension ViewController {
    func prefixTb() -> Void {
        
    }
}

extension ViewController {
    func shoppingCar() -> Void {
        
        //==================================================================================================================
        //        系统的webview
        //==================================================================================================================
        
        let page = AlibcTradePageFactory.myCartsPage()
        let service = AlibcTradeSDK.sharedInstance().tradeService()

        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
        showParams.openType = .H5
        showParams.isNeedPush = true
//
//        service?.show(showParams.isNeedPush ? self.navigationController! : self,
//                      page: page,
//                      showParams:showParams,
//                      
//                      taoKeParams: nil,
//                      trackParam: ["track_key":"track_value"], tradeProcessSuccessCallback: { (result) in
//                        
//            print("\((#file as NSString).lastPathComponent):(\(#line))\n",result as Any)
//        }, tradeProcessFailedCallback: { (error) in
//            print("\((#file as NSString).lastPathComponent):(\(#line))\n",error as Any)
//        })
        
        
        
//==================================================================================================================
//        自带的webview
//==================================================================================================================
        let pageVC = WebView()
        navigationController?.pushViewController(pageVC, animated: true)
        let aVC = WebView()
        aVC.title = "商品详情"
        
        //自己的webview
        service?.show(showParams.isNeedPush ? self.navigationController! : self,
                      webView: aVC.weView,
                      page: page,
                      showParams: showParams,
                      taoKeParams: nil,
                      trackParam: ["track_key":"track_value"],
                  tradeProcessSuccessCallback: { (result) in
                    print("\((#file as NSString).lastPathComponent):(\(#line))\n",result)
        }, tradeProcessFailedCallback: { (error) in
            print("\((#file as NSString).lastPathComponent):(\(#line))\n",error)
        })
    }
    

    //用自己的webview打开商品详情界面
    func openItemDetatilMyPage(itemId:String) {
        var page = AlibcTradePageFactory.myCartsPage()
        
        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
        showParams.openType = .H5
        showParams.isNeedPush = true
        
        
        page = AlibcTradePageFactory.itemDetailPage(itemId)
        showParams.openType = ALiOpenType.H5
        
        let aVC = WebView()
        
        self.navigationController?.present(aVC, animated: true, completion: {
        
            AlibcTradeSDK.sharedInstance().tradeService().show(showParams.isNeedPush ? self.navigationController! : self, webView: aVC.weView, page: page, showParams: showParams, taoKeParams: nil, trackParam: nil, tradeProcessSuccessCallback: { (result) in
                print("\((#file as NSString).lastPathComponent):(\(#line))\n",result!)
            
            }) { (error) in
                print("\((#file as NSString).lastPathComponent):(\(#line))\n",error as Any)
            }
        })
    }
}

extension ViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        print("\((#file as NSString).lastPathComponent):(\(#line))\n",self.childViewControllers.count)
        
        if self.childViewControllers.count > 1 {
            self.hidesBottomBarWhenPushed = true
        } else {
            self.navigationController?.toolbar.isHidden = false
        }
    }
}
